/*
 * @Description:
 * @Author: zekit
 * @Date: 2022-01-28 14:04:58
 * @LastEditors: zekit
 * @LastEditTime: 2022-02-17 16:15:21
 */
import { asyncRoutes, constantRoutes } from '@/router'
// import ro from 'element-ui/src/locale/lang/ro'

/**
 *
 * 该文件作用：通过用户的权限和之前在router.js里面asyncRouterMap的每一个页面所需要的权限做匹配，最后返回一个该用户能够访问路由有哪些。
 * 使用 meta.role 判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * 通过递归过滤异步路由表,返回符合用户角色权限的路由表
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {

      // 是否存在子节点，存在子节点说明当前节点为展开栏，并非页面
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)//判断权限的
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      // 通过判断如果用户是admin管理员 就直接把整个权限目录都加载，如果不是再进行过滤
      let accessedRoutes
	    console.log('asyncRoutes ---', asyncRoutes)
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      // console.log('accessedRoutes ---', accessedRoutes)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
